﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Search.Administration;

namespace SharePointOnlineCmdlets
{
    /// <summary>
    /// Imports a search configuration xml file for SharePoint Online
    /// </summary>
    [Cmdlet(VerbsData.Import, "SPOSearchConfig")]
    public class ImportSPOSearchConfig : PSCmdlet
    {
        [Parameter(Mandatory = true, ValueFromPipeline = true)]
        public ClientContext Context { get; set; }

        [Parameter(Mandatory = true)]
        public string Path { get; set; }

        [Parameter(Mandatory = true)]
        public string Scope { get; set; }

        protected override void ProcessRecord()
        {
            var scope = SearchObjectLevel.SPSiteSubscription;
            SearchObjectLevel.TryParse(Scope, true, out scope);
            var searchConfigurationPortability = new Microsoft.SharePoint.Client.Search.Portability.SearchConfigurationPortability(Context);
            var owner = new SearchObjectOwner(Context, scope);
            var searchConfiguration = System.IO.File.ReadAllText(Path);
            searchConfigurationPortability.ImportSearchConfiguration(owner, searchConfiguration);
            Context.ExecuteQuery();
        }
    }
}
